<?php
/**
 * Created by PhpStorm.
 * User: zq
 * Date: 2018/3/20
 * Time: 13:21
 */

use Helper\DbConf;
use eYaf\Logger;

require APP_PATH . "/vendor/autoload.php";

class ScriptController extends ApplicationController
{

    const LIMIT = 100;

    const IMG_DOMAIN = 'http://c01.banhai.com';
    const IMG_DOMAIN_OTHER = 'http://www.banhai.com';

    const OPTION = [
        1 => 'A',
        2 => 'B',
        3 => 'C',
        4 => 'D',
        5 => 'E',
        6 => 'F',
        7 => 'G',
        8 => 'H',
    ];


    public function init()
    {

        parent::init();
        DbConf::i();
    }

    /**
     * 处理小学题目的选项和答案
     */
    public function optionAction()
    {

        $this->log("begin...\n\n");

        while (true) {

            $res = PrimaryQuestionModel::get([], 0, self::LIMIT);
            if (!$res) {
                $this->log("\n\nall finished...\n");
                exit;
            }

            foreach ($res as $v) {

                $id = $v->id;
                $this->log("id:$id");
                $v->answer = $this->convertStrType($v->answer);
                $v->stem = $this->convertStrType($v->stem);

                //提取答案
                preg_match_all("/<tr><td>(.*?)<\/td><\/tr>/s", $v->answer, $ma);
                $answer = $ma[1][0] ?? [];

                $answer = preg_replace("/<p>(.*?)<\/p>/s", "$1", $answer);
                $answer = trim($answer);
                if (!$answer) {
                    $data = ['p_answer_ok' => 2, 'p_option_ok' => 2,];
                    PrimaryQuestionModel::update($id, $data);

                    $this->log("id:{$id},匹配失败");
                    continue;
                }

                if (strpos($answer, '或') !== false) {
                    $data = ['p_answer_ok' => 2, 'p_option_ok' => 2,];
                    PrimaryQuestionModel::update($id, $data);

                    $this->log("id:{$id},答案不唯一");
                    continue;
                }

                $answer_arr = str_split($answer);
                $p_answer = $answer;


                //提取选项
                preg_match_all("/<tr><td>(.*?)<\/td><\/tr>/s", $v->stem, $ma);
                $content = $ma[1] ?? [];
                if (empty($content[0]) || empty($content[2])) {
                    $this->log("id:{$id},题干/选项匹配失败");
                    continue;
                }

                $p_stem = $content[0];

                $option_arr = explode('<br>', $content[2]);

                $new_option_arr = [];
                foreach ($option_arr as $ko => $vo) {
                    $tmp = explode('.', $vo);
                    $option_id = $ko + 1;

                    $opt_a = self::OPTION[$option_id];
                    $is_right = in_array($opt_a, $answer_arr) ? 1 : 2;

                    $new_option_arr[] = [
                        'option_id' => $option_id,
                        'option_trunk' => $tmp[1],
                        'is_right' => $is_right,
                    ];
                }

                $p_option = json_encode($new_option_arr);

                $data = [
                    'p_stem' => $p_stem,
                    'question_option' => $p_option,
                    'p_option_ok' => 1,
                    'right_answer' => $p_answer,
                    'p_answer_ok' => 1,
                ];
                PrimaryQuestionModel::update($id, $data);
            }

            $this->log("finished...");
            sleep(1);

        }

        $this->log("all finished...");
    }

    /**
     * 处理01次提供的初高中题库数据处理：
     * 1. 从题干中分离选择题选项
     * 2. 格式化选择题及判断题的答案，去除混乱字符
     * @throws Exception
     */
    public function cgzAction()
    {
        $dao = new TestTikuCgz01Model();
        $dao->paseData();
        $this->json(null, '处理完毕');
    }


    /**
     * bh初高中题库图片处理：图片下载
     */
    public function imageAction()
    {

        $this->log(date('Y-m-d H:i:s') . 'start...');

        while (true) {
            $res = TestTikuXx01Model::get([], 0, self::LIMIT);
            if (!$res) {
                $this->log("\n\n " . date('Y-m-d H:i:s') . " all finished...");
                exit;
            }

            foreach ($res as $v) {
                $id = $v->id;
                $str = $v->content . $v->analytical;
                preg_match_all('@src="(.*?)"@', $str, $ma);

                $this->log(date('H:i:s') . "--------------------开始:qid = $id ---------------------");

                $img_arr = $ma[1] ?? [];
                //没有图片，更新状态
                if (!$img_arr) {
                    $data = ['p_img_ok' => 1,];
                    TestTikuXx01Model::update($id, $data);
                    continue;
                }

                //处理图片
                $not_exist_img = [];
                $fileList = [];
                foreach ($img_arr as $vo) {
                    $img_url = self::IMG_DOMAIN . $vo;
                    $exist = $this->fileExist($img_url);
                    if (!$exist) {
                        $img_url = self::IMG_DOMAIN_OTHER . $vo;
                        $exist = $this->fileExist($img_url);
                    }

                    //不存在的图片记录下来
                    if (!$exist) {
                        $not_exist_img[] = $vo;
                        continue;
                    }

                    //下载图片
                    $dir = dirname(PUBLIC_PATH . $vo) . '/';

                    $this->mkdirs($dir);

                    $this->log(date('H:i:s') . $img_url);
                    $this->downloadImage($img_url, $dir);
                    $fileList[] = [
                        'url' => $vo,
                        'type' => 1,
                    ];
                }

                //更新数据库状态
                $data = [
                    'p_img_error' => $not_exist_img ? implode('|||', $not_exist_img) : '',
                    'p_img_ok' => $not_exist_img ? 2 : 1,
                    'file_list' => json_encode($fileList),
                ];

                TestTikuXx01Model::update($id, $data);

                $msg = date('H:i:s') . "--------------------结束:qid= $id ---------------------";
                $this->log($msg);
            }

            $this->log(date('Y-m-d H:i:s') . 'finished...');

            sleep(1);
        }

    }


    private function mkdirs($dir, $mode = 0777)
    {
        if (is_dir($dir) || @mkdir($dir, $mode)) {
            return true;
        }
        if (!$this->mkdirs(dirname($dir), $mode)) {
            return false;
        }

        return @mkdir($dir, $mode);
    }


    private function downloadImage($url, $path = 'images/')
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
        $file = curl_exec($ch);
        curl_close($ch);

        $this->saveAsImage($url, $file, $path);
    }

    private function saveAsImage($url, $file, $path)
    {
        $filename = pathinfo($url, PATHINFO_BASENAME);
        $resource = fopen($path . $filename, 'a');
        fwrite($resource, $file);
        fclose($resource);
    }

    private function fileExist($url)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_NOBODY, 1); // 不下载
        curl_setopt($ch, CURLOPT_FAILONERROR, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        if (curl_exec($ch) !== false) {
            return true;
        }
        return false;
    }

    private function log($msg)
    {
        Logger::getLogger()->log($msg);
        echo date('Y-m-d H:i:s') . "\t$msg\n<br>";
    }


    /**
     * 字符串半角和全角间相互转换
     * @param string $str 待转换的字符串
     * @param int $type TODBC:转换为半角；TOSBC，转换为全角
     * @return string 返回转换后的字符串
     */
    private function convertStrType($str, $type = 'TOSBC')
    {

        $dbc = [
            '０', '１', '２', '３', '４',
            '５', '６', '７', '８', '９',
            'Ａ', 'Ｂ', 'Ｃ', 'Ｄ', 'Ｅ',
            'Ｆ', 'Ｇ', 'Ｈ', 'Ｉ', 'Ｊ',
            'Ｋ', 'Ｌ', 'Ｍ', 'Ｎ', 'Ｏ',
            'Ｐ', 'Ｑ', 'Ｒ', 'Ｓ', 'Ｔ',
            'Ｕ', 'Ｖ', 'Ｗ', 'Ｘ', 'Ｙ',
            'Ｚ', 'ａ', 'ｂ', 'ｃ', 'ｄ',
            'ｅ', 'ｆ', 'ｇ', 'ｈ', 'ｉ',
            'ｊ', 'ｋ', 'ｌ', 'ｍ', 'ｎ',
            'ｏ', 'ｐ', 'ｑ', 'ｒ', 'ｓ',
            'ｔ', 'ｕ', 'ｖ', 'ｗ', 'ｘ',
            'ｙ', 'ｚ', '－', '　', '：',
            '．', '，', '／', '％', '＃',
            '！', '＠', '＆', '（', '）',
            '＜', '＞', '＂', '＇', '？',
            '［', '］', '｛', '｝', '＼',
            '｜', '＋', '＝', '＿', '＾',
            '￥', '￣', '｀',
        ];

        $sbc = [//半角
            '0', '1', '2', '3', '4',
            '5', '6', '7', '8', '9',
            'A', 'B', 'C', 'D', 'E',
            'F', 'G', 'H', 'I', 'J',
            'K', 'L', 'M', 'N', 'O',
            'P', 'Q', 'R', 'S', 'T',
            'U', 'V', 'W', 'X', 'Y',
            'Z', 'a', 'b', 'c', 'd',
            'e', 'f', 'g', 'h', 'i',
            'j', 'k', 'l', 'm', 'n',
            'o', 'p', 'q', 'r', 's',
            't', 'u', 'v', 'w', 'x',
            'y', 'z', '-', ' ', ':',
            '.', ',', '/', '%', ' #',
            '!', '@', '&', '(', ')',
            '<', '>', '"', '\'', '?',
            '[', ']', '{', '}', '\\',
            '|', '+', '=', '_', '^',
            '￥', '~', '`',
        ];
        if ($type == 'TODBC') {
            return str_replace($sbc, $dbc, $str); //半角到全角
        } elseif ($type == 'TOSBC') {
            return str_replace($dbc, $sbc, $str); //全角到半角
        } else {
            return $str;
        }
    }


}